package user_information;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONObject;

import DB.DB_connection_pool;

public class Password_modify extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		PrintWriter out = response.getWriter();
		
		String user_account = request.getSession().getAttribute("user_account").toString();
		String old_user_password = request.getParameter("old_user_password");
		String new_user_password = request.getParameter("new_user_password");
		
		String select_sql = "select * from land_table where user_account = '"+user_account+"'";
		String update_sql = "update land_table set user_password = '"+new_user_password+"' where user_account = '"+user_account+"'";
		
		JSONObject jsonObj = new JSONObject();
		try {
			Connection conn = DB_connection_pool.data_pool.getConnection();
			PreparedStatement ps_select= conn.prepareStatement(select_sql);
			ResultSet rs = ps_select.executeQuery();
			
			if(rs.next()){
				String user_password = rs.getString("user_password");
				if(user_password.equals(old_user_password)){
					PreparedStatement ps_update = conn.prepareStatement(update_sql);
					ps_update.executeUpdate();
					
					jsonObj.put("result", true);
					ps_update.close();
				}else{
					jsonObj.put("result", false);
				}
			}else{
				jsonObj.put("result", false);
			}
			
			rs.close();
			ps_select.close();
			conn.close();
		} catch (SQLException e) {
			jsonObj.put("result", false);
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		out.print(jsonObj.toString());
	}

}
